<template>
  <input type="file" ref="fileInput" @change="handleFileChange" class="hidden" />
  <div class="w-[240px] h-[100px] bg-gray-100 text-gray-500 flex items-center flex-col justify-center"
    @click="handleClick">
    <template v-if="!dialogImageUrl">
      <span> + 上传图片</span>
      <span>建议尺寸480 * 200</span>
    </template>
    <img w-full v-if="dialogImageUrl" class="w-full h-full" :src="dialogImageUrl" alt="Preview Image" />
  </div>

  <el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, defineModel } from 'vue'
import { uploadImage } from '@/api/upload'

const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const imgUrl = defineModel()
const fileInput = ref()

// 监听imgUrl变化，同步更新dialogImageUrl

const handleClick = () => {
  fileInput.value.click()
}

const handleFileChange = (e: { target: any }) => {
  console.log(e.target.files)
  const file = e.target.files[0]
  if (file) {
    dialogImageUrl.value = URL.createObjectURL(file)
  }
  const formData = new FormData()
  formData.append('file', file)
  uploadImage(formData).then((res) => {
    console.log(res)
    imgUrl.value = import.meta.env.VITE_REQUEST_BASE_URL + res.data.url
  })
}


</script>
